//
//  SheetCollectionView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/28.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
let KCellTag = 2000
protocol SheetCollecDelegate: class {
    func changeHeight(selectBool:Bool,contentHeight:CGFloat)
}
class SheetCollectionView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
    var config:SelectionConfig?
    var model:SelectionModel?
    weak var delegate:SheetCollecDelegate?
    var dataSource:SelectmangerDelegate?
    var collectionView:UICollectionView?
    var layout:SheetLayout?
    lazy var coinTextField:BaseTextField = {
       let textfield = BaseTextField(changeView: self.superview, szBounds: CGRect(x: 16, y: 0, width: (kSCREEN_WIDTH-55)/2-21, height: 40))
        textfield.delegate = self
        textfield.font = UIFont.systemFont(ofSize: 13)
        textfield.themeTextColor = ThemeManager.ThemeColorKeys.text1
        textfield.layer.borderWidth = 0.5
        textfield.layer.borderColor = KUseTitleColor.cgColor
        textfield.layer.cornerRadius = 3
        textfield.placeholder = kText("币种")
        textfield.setValue(UIFont.systemFont(ofSize: 12), forKeyPath: "_placeholderLabel.font")
        textfield.setValue(UIColor(hexStr:"#c0c0c0"), forKeyPath: "_placeholderLabel.textColor")
       return textfield
    }()
    lazy var kindBtn:CustomBtn =  {
        let btn = CustomBtn()
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = KUseTitleColor.cgColor
        btn.layer.cornerRadius = 3
        btn.photoImageView.image = UIImage(named: "leverDown")
        btn.addTarget(self, action: #selector(kindBtnAction), for: UIControlEvents.touchUpInside)
        return btn
    }()
    var openSelectBool = false //是否点击选择计价单位
    var coinPairArr:[String] = [] //币种对名称
    init(config:SelectConfig ,model:SheetModel ,dataSource:SelectmangerDelegate) {
        super.init(frame: CGRect.zero)
        self.config = config as? SelectionConfig
        self.model = model as? SelectionModel
        self.dataSource = dataSource
        self.themeBackground = ThemeManager.ThemeColorKeys.background
    
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() {
        let layout = SheetLayout(style: (self.config?.style)!)
        self.layout = layout
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        self.collectionView = collectionView
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.themeBackground = ThemeManager.ThemeColorKeys.background
        collectionView.register(LeverSectionCollectionViewCell.self, forCellWithReuseIdentifier: "identifier")
        self.addSubview(collectionView)
        collectionView.register(LeverSelectCollectionViewCell.self, forCellWithReuseIdentifier: "identifier1")
        self.addSubview(collectionView)
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collettionSectionHeader")
        collectionView.snp.makeConstraints { (make) in
            make.top.bottom.right.left.equalToSuperview()
        }
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        self.collectionView?.collectionViewLayout.invalidateLayout()
        return model!.leverSheetArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return openSelectBool ? model!.leverSheetArr[section].count : 0
        }else {
            return model!.leverSheetArr[section].count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let smModel = model!.leverSheetArr[indexPath.section][indexPath.row]
        if smModel.style == .sectionStyle {
            let cell:LeverSectionCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! LeverSectionCollectionViewCell
            cell.nameLabel.text  = smModel.name
            return cell
            
        }else {
        let cell:LeverSelectCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier1", for: indexPath) as! LeverSelectCollectionViewCell
        cell.tag = KCellTag*indexPath.section + indexPath.row
        
        cell.titleLabel.text = smModel.name
        cell.selectImage.isHidden = !smModel.selectBool
        if (indexPath.section == 3 || indexPath.section == 5) && smModel.name == kText("确定") {
            cell.titleLabel.layer.borderWidth = 0
            cell.titleLabel.backgroundColor = kThemeColor
            cell.titleLabel.textColor = UIColor.white
        }else {
        cell.titleLabel.backgroundColor = UIColor.clear
            cell.titleLabel.layer.borderWidth = 0.5
         if smModel.selectBool {
            cell.titleLabel.textColor = kThemeColor
        }else{
            cell.titleLabel.themeTextColor = ThemeManager.ThemeColorKeys.text2
        }
        cell.titleLabel.layer.borderColor = cell.titleLabel.textColor.cgColor
        }
        return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collettionSectionHeader", for: indexPath)
        
        let titleLabel = BaseLabel(style: .oneStyle)
        view.addSubview(titleLabel)
        titleLabel.text = kText("筛选")
        //
        titleLabel.font = UIFont(name: "PingFang-SC-Heavy", size: 17)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(25)
            make.left.equalToSuperview().offset(15)
        }
        
        let nameLabel = BaseLabel(style: .twiceStyle)
        view.addSubview(nameLabel)
        nameLabel.text = kText("交易对")
        nameLabel.font = UIFont.systemFont(ofSize: 12)
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(65)
        }

        view.addSubview(coinTextField)
        coinTextField.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(89)
            make.width.equalTo((kSCREEN_WIDTH-55)/2)
            make.height.equalTo(40)
        }
      
        kindBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        kindBtn.setTitleColor(kTextColor, for: UIControlState.normal)
        if self.model?.sourceCoin.count == 0 {
            kindBtn.nameLabel.font = UIFont.systemFont(ofSize: 12)
            kindBtn.nameLabel.textColor = UIColor(hexStr:"#c0c0c0")
            kindBtn.nameLabel.text = kText("选择计价单位")
        }else {
            kindBtn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text1
            kindBtn.nameLabel.text = self.model?.sourceCoin
        }

        view.addSubview(kindBtn)
        kindBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(90)
            make.width.equalTo((kSCREEN_WIDTH-55)/2)
            make.height.equalTo(40)
        }
        kindBtn.nameLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        kindBtn.photoImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-10)
            make.centerY.equalToSuperview()
        }
        
        let xgImageView = UIImageView(image: UIImage(named: "xg"))
        view.addSubview(xgImageView)
        xgImageView.snp.makeConstraints { (make) in
            make.centerY.equalTo(kindBtn)
            make.centerX.equalToSuperview()
        }
    
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
         return CGSize(width: kSCREEN_WIDTH, height: 114)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if config?.style == .leverSelectStyle {
            switch indexPath.section {
            case 0:
                self.model?.sourceCoin = (self.model?.leverSheetArr[0][indexPath.row].name)!
                self.changeBuyStyle(section:indexPath.section,row: indexPath.row)
                self.collectionView?.reloadData()
                break
            case 2:
                self.model?.orderType = (self.model?.leverSheetArr[indexPath.section][indexPath.row].name)!
                self.changeBuyStyle(section: indexPath.section, row: indexPath.row)
                collectionView.reloadData()
                break
            case 4:
                self.model?.orderType = (self.model?.leverSheetArr[indexPath.section][indexPath.row].name)!
                self.changeBuyStyle(section: indexPath.section, row: indexPath.row)
                collectionView.reloadData()
                break
            case 5:
            
                break
                
            default:
                break
            }
            return
        }
        if indexPath.section == 0 {
            self.model?.sourceCoin = (self.model?.leverSheetArr[0][indexPath.row].name)!
            self.changeBuyStyle(section:0,row: indexPath.row)
            openSelectBool = false
            self.collectionView?.reloadData()
            if delegate != nil && ((delegate?.changeHeight) != nil) {
                delegate?.changeHeight(selectBool: false,contentHeight:0)
            }
        }else if indexPath.section == 2{
            if indexPath.row == 0 {
                self.model?.isBuyBool = true
            }else {
                self.model?.isBuyBool = false
            }
            self.changeBuyStyle(section: indexPath.section, row: indexPath.row)
            collectionView.reloadData()
        }else if indexPath.section == 3 {
            if indexPath.row == 0 {
                openSelectBool = false
                self.model?.isBuyBool = true
                self.model?.targetCoin = ""
                self.model?.sourceCoin = ""
                self.changeBuyStyle(section: 2 ,row: 0)
                coinTextField.text = ""
                kindBtn.setTitle("", for: UIControlState.normal)
                collectionView.reloadData()
                if delegate != nil && ((delegate?.changeHeight) != nil) {
                    delegate?.changeHeight(selectBool: false,contentHeight:0)
                }
                
            }else {
                if self.model?.targetCoin.count == 0 {
                    CYMBShow.showMessage(kText("请输入币种名称"))
                    return
                }
                if self.model?.sourceCoin.count  == 0 {
                    CYMBShow.showMessage(kText("请选择交易币种"))
                    return
                }
                let arr = APPTransactionPair.default.searchCoinPair(key: (self.model?.sourceCoin)!)
                let name = String(format: "%@/%@", (model?.targetCoin)!,(model?.sourceCoin)!)
                if !arr.contains(name) {
                    CYMBShow.showMessage(kText("目前不支持该币对交易,请重新选择"))
                    return
                }
                
                if dataSource != nil && dataSource?.selectModel != nil {
                    dataSource?.selectModel(model: self.model!)
                }
                SelectActionManger.manager.close()
            }
        }
    }
    
    func changeBuyStyle(section:Int,row:Int) {
        for (index,model) in (self.model?.leverSheetArr[section].enumerated())! {
            if index == row {
               model.selectBool = true
            }else {
                model.selectBool = false
            }
        }
    }
    
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
       return true
    }
    
    @objc func kindBtnAction() {

        coinPairArr = APPTransactionPair.default.archiveTitleArray()
        if coinPairArr.count == 0 {
            CYMBShow.showMessage(kText("当前无币对支持交易"))
            return
        }
         self.endEditing(true)
        var arr:[SheetStyleModel] = []
        for (index,name) in coinPairArr.enumerated() {
            let model:SheetStyleModel = SheetStyleModel()
            model.name = name.components(separatedBy: "/").count > 0 ? name.components(separatedBy: "/").first! : ""
            if self.model?.sourceCoin.count == 0 && index == 0{
                model.selectBool = true
            }else {
                if self.model?.sourceCoin == model.name {
                    model.selectBool = true
                }
            }
            model.style = .commonStyle
            arr.append(model)
        }
        self.model?.leverSheetArr.remove(at: 0)
        self.model?.leverSheetArr.insert(arr, at: 0)
        openSelectBool = true
        if delegate != nil && ((delegate?.changeHeight) != nil) {
            let height = CGFloat(Int(coinPairArr.count/3)*35) - 30
            delegate?.changeHeight(selectBool: true,contentHeight:height)
        }
        collectionView?.reloadData()
    }
    
    
    func changeStates(index:NSIndexPath) {
        if index.section == 0 {
            
            
        }else if index.section == 2 {
            
        }else {
            
            
        }
        
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension SheetCollectionView:UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if string.count == 0 {
            return true
        }
        if newString.count > 10 {
            return false
        }
        if textField.judgePassRule(pass: string) {
            textField.text = newString.uppercased()
            self.model?.targetCoin = textField.text!
            return false
        }
        return false
        
    }
    
}
